// 全局注册组件
Vue.component('choice-address', {
    template: `
        <div class="address-main" v-if="isaddress">
            <div class="address-header"><i class="address-goback" @click="goback()">返回</i>{{headerTitle}}</div>
            <div v-if="showType === 0">
                <div class="address-headerInputBox">
                    <span>深圳</span><form action="javascript:void(0);"><input type="search" v-model="key" placeholder="请输入小区名称" class="address-headerInput" @keypress="addSearch"></form>
                </div>

                <div class="address-container">
                    <cube-scroll
                        ref="addressList"
                        :data="addressList"
                        :options="scrollOptions"
                        @pulling-up="searchMore">
                        <ul v-if="addressList && addressList.length > 0">
                            <li class="address-list" v-for="(item,index) in addressList" :key="index" @click="choiceAddress(item)">
                                <h1 class="address-listTitle" v-html="item.name"></h1><p class="address-listAddress">{{item.fullName}}</p>
                            </li>
                        </ul>
                        <div class="address-noResult" v-else-if="addressList && addressList.length === 0">
                            <div>暂无结果</div>
                            <a class="address-btnAdd" @click="newAdd">添加小区</a>
                        </div>
                    </cube-scroll>
                </div>
            </div>

            <div class="address-inputContainer" v-else-if="showType === 1">
                <div class="address-inputBox">
                    <div class="address-inputLeft">市区街道：</div>
                    <div class="address-inputRight" @click="changeStreet">{{street}}</div>
                </div>
                <div class="address-inputBox">
                    <div class="address-inputLeft">小区名：</div>
                    <div class="address-inputRight"><input class="address-input" type="text" v-model="communityName" placeholder="请输入小区名称"/></div>
                </div>
                <cube-button class="address-btnSubmit" :primary="true" @click="submit">添加小区</cube-button>
            </div>
        </div>
    `,
    props: ['isaddress'],
    data() {
        return {
            pullUpLoad: false,
            pullUpLoadThreshold: 0,
            pullUpLoadNoMoreTxt: '没有更多了！',
            addressList: null,
            loading: true,
            currentPage: 1,
            pageSize: 20,
            totalPage: 2,
            key: '',
            showType: 0,
            headerTitle: '选择您的地址',
            street: '请选择市区街道',
            communityName: '',
            addressData: null,
            smallCommunityId: null
        }
    },
    computed: {
        scrollOptions () {
            return {
                pullUpLoad: this.pullUpLoadObj
            }
        },
        pullUpLoadObj: function() {
            return this.pullUpLoad ? {
                threshold: parseInt(this.pullUpLoadThreshold),
                txt: {
                    noMore: this.pullUpLoadNoMoreTxt
                }
            } : false
        }
    },
    /* watch: {
        key (val) {
            if (val.length > 0) {
                this.pullUpLoad = true
                this.currentPage = 1
                this.getSearchData()
            } else {
                this.addressList = null
                this.pullUpLoad = false
            }
        }
    }, */
    methods: {
        // 返回
        goback () {
            if (this.showType === 0) {
                this.closeAddress()
                this.addressList = null
            } else if (this.showType === 1) {
                this.showType = 0
                this.headerTitle = '选择您的地址'
                this.street = '请选择市区街道'
                this.communityName = ''
                this.smallCommunityId = null
            }
        },
        // 搜索小区弹窗关闭
        closeAddress () {
            this.$emit('change' , false)
        },
        addSearch (event) { 
            if (event.keyCode == 13) { //如果按的是enter键 13是enter
                this.getSearchData()
            } 
        },
        // 无限加载小区数据
        searchMore () {
            this.currentPage ++
            if(this.currentPage > this.totalPage){
                this.loading = true
                this.$refs.addressList.forceUpdate()
                return
            }
            this.getSearchData()
        },
        // 获取小区数据
        getSearchData () {
            Axios.post('area/area/getSmallCommunityByKey.do', {
                key: this.key,
                currentPage: this.currentPage,
                pageSize: this.pageSize
            }).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data.data
                    let reg = new RegExp(this.key, 'g')
                    list.forEach(item => {
                        item.name = item.name.replace(reg, '<i>' + this.key +'</i>')
                    })
                    if (this.currentPage === 1) {
                        this.addressList = list
                    } else {
                        this.addressList = this.addressList.concat(list)
                    }
                    this.totalPage = res.data.totalPage

                    if (this.currentPage >= this.totalPage) {
                        this.loading = true
                        this.$refs.addressList.forceUpdate()
                    } else {
                        this.loading = false
                    }
                } else {
                    this.addressList = []
                }
            })
        },
        // 选择小区
        choiceAddress (item) {            
            let reg = new RegExp('<i>', 'g')
            let reg1 = new RegExp('</i>', 'g')
            item.name = item.name.replace(reg, '')
            item.name = item.name.replace(reg1, '')
            let data = {
                houseEstate: item.name,
                fullAddress: item.fullName,
                addressOne: item.smallCommunityId
            }
            this.$emit('choice', data)
            this.closeAddress()
            this.key = ''
            this.currentPage = 1
            this.addressList = null
        },
        newAdd () {
            if (this.key) {
                this.communityName = this.key
            }
            this.showType = 1
            this.headerTitle = '添加小区'
        },
        changeStreet () {
            Axios.post('area/area/getAllArea.do', {}).then(res => {
                if (res.respCode === 'S') {
                    let list = res.data[0].child
                    let addressData = []
                    list.forEach(h1 => {
                        let data = {
                            value: h1.code,
                            text: h1.name,
                            children: []
                        }
                        h1.child.forEach(h2 => {
                            let areaData = {
                                value: h2.code,
                                text: h2.name,
                                children: []
                            }
                            h2.child.forEach(h3 => {
                                let streetData = {
                                    value: h3.code,
                                    text: h3.name
                                }
                                areaData.children.push(streetData)
                            })
                            data.children.push(areaData)
                        })
                        addressData.push(data)
                    })
                    /* let addressData = list.map(h1 => {
                        let areaData = h1.child.map(h2 => {
                            let streetData = h2.child.map(h3 => {
                                let data = {
                                    value: h3.code,
                                    textL: h3.name
                                }
                                return data
                            })
                            let areaData = {
                                value: h2.code,
                                text: h2.name,
                                children: streetData
                            }
                            return areaData
                        })
                        let data = {
                            value: h1.code,
                            text: h1.name,
                            children: areaData
                        }
                        return data
                    }) */
                    this.addressData = addressData
                    this.addressPick()
                    this.addressPicker.show()
                } else {
                    this.$createToast({
                        txt: res.errorMsg,
                        type: 'txt',
                        time: 1000
                    }).show()
                }
            })
        },
        addressPick () {
            this.addressPicker = this.$createCascadePicker({
                title: '选择市区街道',
                data: this.addressData,
                onSelect: this.selectHandle,
                onCancel: this.cancelHandle
            })
        },
        selectHandle(selectedVal, selectedIndex, selectedText) {
            this.street = selectedText.join('')
            this.smallCommunityId = selectedVal[2]
            /* this.$createDialog({
                type: 'warn',
                content: `Selected Item: <br/> - value: ${selectedVal.join(', ')} <br/> - index: ${selectedIndex.join(', ')} <br/> - text: ${selectedText.join(' ')}`,
                icon: 'cubeic-alert'
            }).show() */
        },
        cancelHandle() {
            this.$createToast({
                type: 'correct',
                txt: '请选择市区街道',
                time: 1000
            }).show()
        },
        submit () {
            if (this.street === '请选择市区街道' || !this.street) {
                this.$createToast({
                    txt: '请选择市区街道',
                    type: 'txt',
                    time: 1000
                }).show()
                return
            }
            if (!this.communityName) {
                this.$createToast({
                    txt: '请输入小区名称',
                    type: 'txt',
                    time: 1000
                }).show()
                return
            }
            Axios.post('area/SmallCommunity/addSmallCommunity.do', {
                areaCode: this.smallCommunityId,
                name:this.communityName
            }).then(res => {
                if (res.respCode === 'S') {
                    let data = {
                        houseEstate: this.communityName,
                        fullAddress: this.street,
                        addressOne: res.data
                    }
                    this.$emit('choice', data)
                    this.closeAddress()
                } else {
                    this.$createToast({
                        txt: res.errorMsg,
                        type: 'txt',
                        time: 1000
                    }).show()
                }
            })
        }
    }
});